// Copyright 2012 Google Inc. All Rights Reserved.

package com.google.superlists.model;

import com.google.common.collect.Lists;

import java.util.Iterator;
import java.util.List;

/**
 * Represents the content of a super list. This is used to differentiate
 * between the information stored in File metadata and information stored as
 * a JSON blob in the file content.
 *
 * @author sven@google.com (Sven Mawson)
 */
public class SuperListContent {

  /**
   * Returns a content object parsed from the given json.
   */
  public static SuperListContent fromJson(String json) {
    // Legacy support for old content, wrap in fake object.
    if (json.startsWith("[")) {
      json = "{\"items\":" + json + "}";
    }
    return JsonUtil.fromJson(json, SuperListContent.class);
  }

  /** Tasklist this list is linked to. (tasklist.id) */
  public String tasklistId;

  /** Calendar event this list is linked to. (event.id) */
  public String eventId;

  /** Due date of the entire list, as YYYY-MM-DD. (event.start) */
  public String dueDate;

  /** List of items within this list. */
  public List<SuperListItem> items = Lists.newArrayList();

  /** Public constructor for GSON. */
  public SuperListContent() {}

  /**
   * Returns the json representation of this content.
   */
  public String toJson() {
    return JsonUtil.toJson(this);
  }

  /** Remove empty items from the items collection, used during save. */
  void removeEmptyItems() {
    Iterator<SuperListItem> itemIter = items.iterator();
    while (itemIter.hasNext()) {
      SuperListItem next = itemIter.next();
      if (next.name.trim().isEmpty()) {
        itemIter.remove();
      }
    }
  }

  @Override
  public String toString() {
    return tasklistId + ": " + items;
  }
}
